<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\app\XhappState;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Complex\Exception;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;
use Helpers\HttpClient;
use Helpers\XhException;
use Modules\Power;
use Modules\School;
use Services\App;
use Services\ConfigManage;

class AppserverController extends ControllerBase
{

    /**
     * @var HttpClient
     */
    public $httpClient;
    private $appEnum    = [
        'userType'          => [1 => '学生', 2 => '教师', 3 => '家长', 4 => '通用'],
        'installPosition'   => [1 => 'SD卡', 2 => '系统目录'],
        'network'           => [1 => '3GWIFI', 2 => 'WIFI', 3 => '3G', 4 => '禁用'],
        'updateLevel'       => [1 => '无需更新', 2 => '推荐更新', 3 => '强制更新'],
        'programType'       => [0 => '应用', 1 => '插件', 2 => '外部应用'],
        'permission'        => [0 => '全部禁止', 1 => '允许清数据', 2 => '允许卸载', 3 => '全部允许']
    ];
    private $appBool    = ['independent', 'outside', 'show'];
    private $appTime    = ['createTime', 'updateTime', /*'verCreateTime'*/ 'updatedAt'];
    private $whiteEnum  = [
        'retainType'        => [1 => '系统保留', 2 => '公司应用'],
        'status'            => [1 => '启用', 2 => '禁用']
    ];
    private $wallEnum   = [
        'network'           => [1 => '3GWIFI', 2 => 'WIFI', 3 => '3G', 4 => '禁用'],
        'status'            => [1 => '启用', 2 => '禁用']
    ];

    private $appBackStatus = [0 => '删除' , 1 => '启用' , 2 => '禁用'];

    public function initialize()
    {
        $config = Main::getConfigByName('jAppServer');
        $this->httpClient = new HttpClient($config['url']);
    }

    /**
     * 处理应用版本信息，合并到应用信息内
     *
     * @param $appInfo
     *
     * create by ck 20170626
     */
    private function runApplicationVersion(&$appInfo)
    {
        $verInfo                  = $appInfo['appVersions'][0];
        $verInfo['statement']     = $verInfo['description'];
        unset($verInfo['description'], $verInfo['createTime'], $appInfo['appVersions']);
        $appInfo = array_merge($appInfo, $verInfo);
    }

//    private function runApplicationState(&$appList)
//    {
//        $packageInfo = array_column($appList, 'versionCode', 'packageName');
//        $conditions  = [];
//        foreach ($packageInfo as $packageName => $versionCode) {
//            $conditions[] = "(sAppPackage = '{$packageName}' AND iVersionCode = '{$versionCode}')";
//        }
//        $states = XhappState::find([
//            'columns'    => 'sAppPackage,iVersionCode,iState',
//            'conditions' => 'bDelete = 0 AND (' . implode(' OR ', $conditions) . ')',
//        ]);
//    }

    /**
     * 处理应用枚举，布尔值，时间戳等信息
     *
     * @param $appInfo
     *
     * create by ck 20170621
     */
    private function runApplicationEnum(&$appInfo)
    {
        foreach ($appInfo as &$row) {
            foreach ($this->appBool as $field) {
                $row[$field] = $row[$field] ? '是' : '否';
            }
            isset($row['url']) and $row['url'] = "<a target='_blank' href='{$row['url']}'>{$row['url']}</a>";
        }
        Tool::runEnum($appInfo, $this->appEnum);
        Tool::runTimestamp($appInfo, $this->appTime);
        Tool::runByteToMByte($appInfo, 'packageSize');
    }

    /**
     * 应用列表页面
     *
     * create by ck 20170621
     */
    public function applicationAction()
    {
        $this->view->pick('appserver/application');
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/appserver/application.js');
        Assets::fileInput();
        Power::exist('App_AppList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));
        Template::exists('App_List', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！'));
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => '搜索：'];
        if (Power::exist('App_AppList_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus'];
            $listButtonArr[] = ['id' => 'bt_list_push', 'text' => '推送', 'icon' => 'fa-send'];
            if (isset(Main::getConfigByName('jAppServer')['synUrl'])) {
                $listButtonArr[] = ['id' => 'bt_list_syn', 'text' => '同步', 'icon' => 'fa-share'];
            }
        }
        if (Power::exist('App_AppList_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_edit_base', 'text' => '修改基本信息', 'icon' => 'fa-pencil'];
            $listButtonArr[] = ['id' => 'bt_list_edit_version', 'text' => '修改版本信息', 'icon' => 'fa-pencil'];
        }
        if (Power::exist('App_AppList_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_off_shelf', 'text' => '下架', 'icon' => 'fa-cart-arrow-down'];
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        if (Power::exist('School_List_Group_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_school_app', 'text' => '更新至学校', 'icon' => 'fa-bank'];
        }
        if (Power::exist('App_AppList_History')) {
            $listButtonArr[] = ['id' => 'bt_list_history_app', 'text' => '历史版本', 'icon' => 'fa-history'];
        }
        $this->view->setVars([
            'List' => Template::createList('List', 'App_List', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form' => Template::createForm('App_List', $this->appEnum),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('App_AppList'))
        ]);
    }

    /**
     * 获取应用列表
     *
     * @param $contact
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170621
     * modify by ck 20170705    可平台选择及输入文字筛选
     * modify by ck 20170706    合并接口
     * modify by ck 20170824    添加参数，可获取多版本
     * modify by ck 20180625    重构
     */
    public function getApplicationAction($contact = false)
    {
        $page = $this->request->getPost('page', 'int', 1);
        $size = $this->request->getPost('rows', 'int', 20);

        $keywords = $this->request->getPost('keywords', 'string');
        $platform = $this->request->getPost('platform', 'string');
        $schoolId = $this->request->getPost('schoolId', 'int');
        $params   = [];
        if ($platform) {
            $params['platform'] = $platform;
        }
        if ($keywords) {
            $params['keywords'] = $keywords;
        }
        if ($contact) {
            $number = Tool::getValue(Main::getConfigByName('jAppServer'), 'number', 3);
            if ($schoolId == 3563) {
                $params['vnStr'] = "1:{$number};4:{$number}"; //上架+待审核
            } else {
                $params['number'] = $number;
            }
        }
        try {
            $data = App::getApplications($page, $size, $params);
            App::runVersion($data['rows'], !!$contact);
            App::runEnum($data['rows']);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 上传应用，解析后返回数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170622
     * modify by ck 20170707    上传后获取历史信息并填充
     * modify by ck 20170727    可通过filePath直接发布应用
     */
    public function uploadApplicationAction()
    {
        set_time_limit(0);
        $this->view->disable();
        if (!$this->request->hasFiles() && !$this->request->get('filePath', 'string')) {
            return $this->sendErrorResponse(400, '未检测到文件或文件路径参数！');
        }
        try {
            if ($this->request->hasFiles()) {
//                $parseConfig = Main::getConfigByName('appParse');
//                $tempPath    = $parseConfig['tempPath'];
                $file = $this->request->getUploadedFiles()[0];
                $filePath = rtrim(TEMP_PATH, '/') . '/' . $file->getName();
                if (!(is_dir(TEMP_PATH) || mkdir(TEMP_PATH, 0777, true))) {
                    return $this->sendErrorResponse(500, "路径{TEMP_PATH}创建失败！");
                }
                if (!is_writeable(TEMP_PATH)) {
                    return $this->sendErrorResponse(500, "路径{TEMP_PATH}无写入权限！");
                }
                if (!$file->moveTo($filePath)) {
                    return $this->sendErrorResponse(500, "文件移动失败！" . $filePath . $file->getError());
                }
            } else {
                $filePath = $this->request->get('filePath', 'string');
            }
            $appInfo = Main::parseAppInfo(realpath($filePath));
            $appInfo = App::getUploadApplication($appInfo);
            return $this->response->setJsonContent($appInfo);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '解析失败：' . $e->getMessage(), $e->getMessage());
        }
    }

    /**
     * 获取应用信息
     *
     * @param $appId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170623
     * modify by ck 20170626    更改使用接口
     * modify by ck 20181015
     */
    public function getApplicationInfoAction($appId)
    {
        if (!$appId) {
            return $this->sendErrorResponse(400, 'appId不能为空！');
        }
        try {
            $appInfo = App::getAppInfoById($appId, 1);
            $verInfo = $appInfo['appVersions'][0];
            $verInfo['statement'] = $verInfo['description'];
            unset($verInfo['description'], $verInfo['createTime'], $appInfo['appVersions']);
            $appInfo = array_merge($appInfo, $verInfo);
            return $this->sendJsonResponse($appInfo);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 发布应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170623
     * modify by fyh 20181213
     */
    public function releaseApplicationAction()
    {
        $appInfo = $this->request->getPost();
        if (!$appInfo) {
            return $this->sendErrorResponse(400, '未检测到有效数据！');
        }
        //处理int类型及bool类型数据
        Tool::runInteger($appInfo, $this->appEnum);
        foreach ($this->appBool as $field) {
            $appInfo[$field] = $appInfo[$field] == 'true' ? true : false;
        }
        $appInfo['versionCode'] = intval($appInfo['versionCode']);
        $appInfo['packageSize'] = intval($appInfo['packageSize']);
        $appInfo['updateLevel'] = intval($appInfo['updateLevel']);
        $appInfo['order'] = intval($appInfo['order']);
//        try {
            App::releaseApplication($appInfo);
            return $this->sendSuccessResponse('发布成功！');
//        } catch (Exception $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
    }

    /**
     * 删除应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170626
     */
    public function delApplicationAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'appId不能为空！');
        }
        try {
            App::delApplication($ids);
            return $this->sendSuccessResponse('删除成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 应用基本信息
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20181015
     */
    public function appBaseAction()
    {
        if (!Power::exist('App_AppList_Edit')) {
            return $this->sendViewError('无操作权限');
        }
        $appId = $this->request->getQuery('appId', 'string');
        if (!$appId) {
            return $this->sendViewError('缺少应用id');
        }
        $this->view->pick('appserver/appBase');
        Assets::importJs('js/appserver/appBase.js');
        try {
            return $this->view->setVars([
                'enum' => App::$enum
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 修改应用基本信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181016
     */
    public function modifyAppBaseAction()
    {
        if (!Power::exist('App_AppList_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $appId   = $this->request->getPost('appId', 'string');
        $appInfo = $this->request->getPost();
        if (!$appId) {
            return $this->sendErrorResponse(400, '缺少应用id');
        }
        unset($appInfo['appId']);
        try {
            App::modifyAppBase($appId, $appInfo);
            return $this->sendSuccessResponse('修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 应用版本信息
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20181018
     */
    public function appVersionAction()
    {
        if (!Power::exist('App_AppList_Edit')) {
            return $this->sendViewError('无操作权限');
        }
        $appId = $this->request->getQuery('appId', 'string');
        if (!$appId) {
            return $this->sendViewError('缺少应用id');
        }
        $this->view->pick('appserver/appVersion');
        Assets::importJs('js/appserver/appVersion.js');
        try {
            return $this->view->setVars([
                'enum' => App::$enum
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取版本信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181018
     */
    public function getAppVersionInfoAction()
    {
        $appId = $this->request->getPost('appId', 'string');
        $versionCode = $this->request->getPost('versionCode', 'int');
        if (!$appId || !$versionCode) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $versionInfo = App::getAppVersionInfo($appId, $versionCode);
            return $this->sendJsonResponse($versionInfo);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 修改应用版本信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181018
     */
    public function modifyAppVersionAction()
    {
        $appId = $this->request->getPost('appId', 'string');
        $versionCode = $this->request->getPost('versionCode', 'int');
        $versionInfo = $this->request->getPost();
//        $description = $this->request->getPost('description', 'string');
//        $updateLevel = $this->request->getPost('updateLevel', 'int');
        if (!$appId || !$versionCode) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            App::modifyAppVersion($appId, $versionCode, $versionInfo);
            return $this->sendSuccessResponse('版本信息修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 同步应用到其他平台
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170728
     * modify by ck 20180319    添加order字段同步
     */
    public function synApplicationAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'appId不能为空！');
        }
        $synUrl = Main::getConfigByName('jAppServer')['synUrl'];
        if (!$synUrl) {
            return $this->sendErrorResponse(400, '缺少配置信息或已关闭同步功能！');
        }
        try {
            $key = $this->di->get('config')->get('key');
            App::synApplication($ids, $synUrl, $key);
            return $this->sendSuccessResponse('同步成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 下架应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180124
     */
    public function setApplicationOffShelfAction()
    {
        $packageName = $this->request->getPost('packageName', 'string');
        if (!$packageName) {
            return $this->sendErrorResponse(400, '缺少包名');
        }
        try {
            App::setApplicationOffShelf($packageName);
            return $this->sendSuccessResponse('下架成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 更新应用到学校
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180124
     * modify by ck 20180524    可选择更新方式
     */
    public function addAppToSchoolAction()
    {
        $packageName = $this->request->getPost('packageName', 'string');
        $versionCode = $this->request->getPost('versionCode', 'int');
        $schoolIds   = $this->request->getPost('schoolIds', 'int');
        $operate     = $this->request->getPost('operate', 'int', 0);
        if (!$packageName || !$versionCode || !$schoolIds) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            App::addAppToSchool($packageName, $versionCode, $schoolIds, $operate);
            return $this->sendSuccessResponse('操作成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 白名单列表页面
     *
     * create by ck 20170627
     */
    public function whiteListAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/appserver/whiteList.js');
        Power::exist('App_White') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));
        Template::exists('App_White', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！'));
        $listButtonArr = [];
        if (Power::exist('App_White_Add')) {
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus'];
        }
        if (Power::exist('App_White_Edit')) {
            $listButtonArr[] = ['id'=>'bt_list_enable', 'text'=>'启用', 'icon'=>'fa-chain'];
            $listButtonArr[] = ['id'=>'bt_list_disable', 'text'=>'禁用', 'icon'=>'fa-chain-broken'];
        }
        if (Power::exist('App_White_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
        }
        $this->view->setVars([
            'List'          => Template::createList('List', 'App_White', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('App_White', $this->whiteEnum),
            'FormButton'    => Template::createButtonToolBar(Main::createFormButton('App_White', 'edit'))
        ]);
    }

    /**
     * 获取白名单列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170627
     * modify by fyh 20181211
     */
    public function getWhiteListAction()
    {
        $page = $this->request->getPost('page', 'int', 1);
        $size = $this->request->getPost('rows', 'int');
        if (empty($page) || empty($size)) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            $body = ConfigManage::appServerGetWhiteList($page, $size);
            if (!$body || $body['totalElements'] === null || $body['content'] === null) {
                return $this->sendErrorResponse(500, '无返回数据');
            }
            $data = [
                'total' => $body['totalElements'],
                'rows'  => $body['content']
            ];
            Tool::runEnum($data['rows'], $this->whiteEnum);
            return $this->response->setJsonContent($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 新增白名单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170627
     * modify by fyh 20181211
     */
    public function createWhiteListAction()
    {
        $whiteInfo = $this->request->getPost();
        if (!$whiteInfo) {
            return $this->sendErrorResponse(400, '无数据！');
        }
        Tool::runInteger($whiteInfo, $this->whiteEnum);
        try {
            ConfigManage::appServerCreateWhiteList($whiteInfo);
            return $this->sendSuccessResponse('添加成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改白名单状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170627
     * modify by fyh 20181211
     */
    public function modifyWhiteListStatusAction()
    {
        $ids    = $this->request->getPost('ids', 'string');
        $status = $this->request->getPost('status', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'id不能为空！');
        }
        $type     = $status == 2 ? '禁用' : '启用';
        try {
            ConfigManage::appServerModifyWhiteListStatus($ids, $status);
            return $this->sendSuccessResponse($type.'成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除白名单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170627
     * modify by fyh 20181211
     */
    public function delWhiteListAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'id不能为空！');
        }
        try {
            ConfigManage::appServerDelWhiteList($ids);
            return $this->sendSuccessResponse('删除成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 防火墙列表
     *
     * create by ck 20170627
     */
    public function firewallAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/appserver/firewall.js');
        Power::exist('App_Firewall') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！'));
        Template::exists('App_Firewall', 'both') or die(Main::showMessageModal('配置文件不存在，请先创建！'));
        $listButtonArr = [];
        if (Power::exist('App_Firewall_Add')) {
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus'];
        }
        if (Power::exist('App_Firewall_Edit')) {
            $listButtonArr[] = ['id'=>'bt_list_enable', 'text'=>'启用', 'icon'=>'fa-chain'];
            $listButtonArr[] = ['id'=>'bt_list_disable', 'text'=>'禁用', 'icon'=>'fa-chain-broken'];
        }
        if (Power::exist('App_Firewall_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
        }
        $this->view->setVars([
            'List'          => Template::createList('List', 'App_Firewall', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('App_Firewall', $this->wallEnum),
            'FormButton'    => Template::createButtonToolBar(Main::createFormButton('App_Firewall', 'edit'))
        ]);
    }

    /**
     * 获取防火墙列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by fyh 20181211
     */
    public function getFirewallAction()
    {
        $page = $this->request->getPost('page', 'int', 1);
        $size = $this->request->getPost('rows', 'int');
        try {
            $body = ConfigManage::appServerGetFirewall($page, $size);
            if (!$body || $body['totalElements'] === null || $body['content'] === null) {
                return $this->sendErrorResponse(500, '无返回数据');
            }
            $data = [
                'total' => $body['totalElements'],
                'rows'  => $body['content']
            ];
            Tool::runEnum($data['rows'], $this->whiteEnum);
            return $this->response->setJsonContent($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 增加防火墙
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by fyh 20181211
     */
    public function createFirewallAction()
    {
        $firewallInfo = $this->request->getPost();
        if (!$firewallInfo) {
            return $this->sendErrorResponse(400, '无数据！');
        }
        Tool::runInteger($firewallInfo, $this->wallEnum);
        try {
            ConfigManage::appServerCreateFirewall($firewallInfo);
            return $this->sendSuccessResponse('添加成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改防火墙状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by fyh 20181211
     */
    public function modifyFirewallStatusAction()
    {
        $ids    = $this->request->getPost('ids', 'string');
        $status = $this->request->getPost('status', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'id不能为空！');
        }
        $type     = $status == 2 ? '禁用' : '启用';
        try {
            ConfigManage::appServerModifyFirewallStatus($ids, $status);
            return $this->sendSuccessResponse($type.'成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改防火墙网络类型
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by fyh 20181211
     */
    public function modifyFirewallNetworkAction()
    {
        $id      = $this->request->getPost('id', 'string');
        $network = $this->request->getPost('network', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, 'id不能为空！');
        }
        try {
            $body = ConfigManage::appServerModifyFirewallNetwork($id, $network);
            Tool::runEnum($body, $this->wallEnum);
            return $this->response->setJsonContent($body);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除防火墙
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by fyh 20181211
     */
    public function delFirewallAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'id不能为空！');
        }
        try {
            ConfigManage::appServerDelFirewall($ids);
            return $this->sendSuccessResponse('删除成功！');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取应用编号枚举
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170801
     */
    public function getAppCodeEnumAction()
    {
        return $this->response->setJsonContent(XhsysEnum::getEnumByNodeName('应用编号'));
    }

    /**
     * 学校应用列表页面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20170828
     */
    public function schoolAppDownAction()
    {
        $this->view->pick('appserver/schoolAppDown');
        Assets::select2('js/appserver/schoolAppDown.js');
        $this->flash->notice('选择学校查看');
        return $this->view->setVars([
            'schoolArr' => XhschoolInfo::getSchoolSupportArray(),
            'typeArr'   => ['' => '全部', 1 => '学生', 2 => '教师']
        ]);
    }

    /**
     * 学校应用设置页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170930
     */
    public function schoolAppAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('appserver/schoolApp');
        Main::showNavPosition('学校列表', ['学校设置', '应用设置'], true);
        Assets::easyUI('js/appserver/schoolApp.js');
        if (!Power::exist('School_List_App')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = [];
        if (Power::exist('School_List_App_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_permission', 'class' => 'menubutton', 'text' => '清数据/卸载', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }
        $listButtonArr[] = ['id' => 'bt_list_version_stats', 'text' => '版本统计', 'icon' => 'fa-eye'];
        return $this->view->setVars([
            'List'          => Template::createList('list', 'App_SchoolApp', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取学校应用列表
     *
     * @param bool $getPermission
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170829
     * modify by ck 20170930    添加权限
     */
    public function getSchoolAppAction($getPermission = false)
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $userType = $this->request->getPost('userType', 'int');
        $response = $this->httpClient->get(sprintf('/api/v1/schools/%d/assigned/apps', $schoolId), $userType ? ['userType' => $userType] : []);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '获取列表失败！', $body->msg ?: $response);
        }
        $rows = $response->toArray();
        $this->runApplicationEnum($rows);

        //组合配置信息
        if ($getPermission) {
            $response = $this->httpClient->get(sprintf('/api/v1/configs/schools/%d/apps', $schoolId));
            if (!$response->isSuccess()) {
                $body = $response->toObject();
                return $this->sendErrorResponse(500, '获取配置失败', $body->msg ?: $response);
            }
            $rows = array_column($rows, null, 'packageName');
            foreach ($response->toArray() as $config) {
                isset($rows[$config['packageName']]) and $rows[$config['packageName']]['permission'] = $this->appEnum['permission'][$config['permission']];
            }
            $rows = array_values($rows);
        }
        return $this->sendJsonResponse($rows);
    }

    /**
     * 设置学校应用权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170930
     */
    public function setSchoolAppPermissionAction()
    {
        $schoolId       = $this->request->getPost('schoolId', 'int');
        $permission     = intval($this->request->getPost('permission', 'int'));
        $packageNames   = $this->request->getPost('packageNames', 'string');
        if (!$schoolId || $permission === '' || !$packageNames) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        $data = [];
        foreach ($packageNames as $packageName) {
            $data[] = ['packageName' => $packageName, 'permission' => $permission];
        }
        $response = $this->httpClient->postJson(sprintf('/api/v1/configs/schools/%d/apps', $schoolId), $data);
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '设置失败', $response);
        }
        return $this->sendSuccessResponse('设置成功');
    }

    /**
     * 学校应用版本安装情况
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180626
     */
    public function schoolAppVersionAction()
    {
        $schoolId    = $this->request->getQuery('schoolId', 'int');
        $packageName = $this->request->getQuery('packageName', 'string');
        if (!$schoolId || !$packageName) {
            return $this->sendViewError('缺少必要参数');
        }
        $this->view->pick('appserver/schoolAppVersion');
        try {
            $data = App::getSchoolAppInstallDetail($schoolId, $packageName);
            foreach ($data['installDTOMap'] as $versionCode => &$detail) {
                Main::runUserName($detail, ['userId' => 'userName']);
            }
            unset($detail);
            return $this->view->setVars([
                'versionInfo'   => $data['appVersionStatisticsDTOList'],
                'versionCode'   => array_keys($data['installDTOMap']),
                'versionDetail' => $data['installDTOMap']
            ]);
        } catch (XhException $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 历史版本管理
     *
     * @return mixed
     *
     * create by qgz 2018/5/4
     * modify by ck 20180912
     */
    public function historyVersionAction()
    {
        $this->view->setTemplateBefore('listForm');
        $appId = $this->request->getQuery('appId', 'string');
        if (!$appId) {
            return $this->sendViewError('缺少应用id');
        }
        Assets::easyUI('js/appserver/appHistoryList.js');
        $listButtonArr = [];
        if (Power::exist('App_AppList_History_Del')) {
            $listButtonArr[] = ['id' => 'bt_history_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if (Power::exist('School_List_Group_Edit')) {
            $listButtonArr[] = ['id'=>'bt_school_app', 'text'=>'更新至学校', 'icon'=>'fa-bank'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('history_list', 'App_History_List', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ]);
    }

    /**
     * 获取历史版本数据
     *
     * @return mixed
     *
     * create by qgz 2018/5/4
     */
    public function getHistoryVersionAction()
    {
        $appId = $this->request->getPost('appId', 'string');
        if (!$appId) {
            return $this->sendErrorResponse(400, '请选择应用！');
        }
        $response = $this->httpClient->get(sprintf('/api/v1/applications/%s', $appId));
        $appInfo  = $response->toArray();
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '获取失败！', $appInfo['msg'] ?: $response);
        }
        foreach ($appInfo['appVersions'] as &$value) {
            if ($value['url']) {
                $value['url'] = "<front title='".$value['url']."'>".$value['url']."</front>";
            }
            if ($value['configURL']) {
                $value['configURL'] = "<front title='".$value['configURL']."'>".$value['configURL']."</front>";
            }
            if ($value['plistUrl']) {
                $value['plistUrl'] = "<front title='".$value['plistUrl']."'>".$value['plistUrl']."</front>";
            }
            $value['appId'] = $appId;
        }
        $varsion = $appInfo['appVersions'];
        unset($appInfo);
        array_multisort(array_column($varsion, 'versionCode'), SORT_DESC, $varsion);
        $data = ['total' => count($varsion), 'rows' => $varsion];
        Tool::runByteToMByte($data['rows'], 'packageSize');
        Tool::runTimestamp($data['rows'], ['updateTime', 'createTime']);
        return $this->sendJsonResponse($data);
    }

    /**
     * 删除历史版本
     *
     * @return mixed
     *
     * create by qgz 2018/5/4
     */
    public function delHistoryAction()
    {
        $appId = $this->request->getPost('appId');
        $versionCode = $this->request->getPost('versionCode');

        if (!$appId || empty($versionCode)) {
            return $this->sendErrorResponse(400, '请选择应用版本！');
        }
        $response = $this->httpClient->delete(sprintf('/api/v1/applications/%1$s/versions/%2$s/', $appId, $versionCode));
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '删除失败！', $body->msg ?: $response);
        }
        return $this->sendSuccessResponse('删除成功！');
    }

    /**
     * 应用黑名单列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180614
     */
    public function appBlacklistAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI();
        Assets::importJs('js/appserver/appBlacklist.js');
        $this->view->pick('appserver/appBlacklist');
        Template::exists('App_Blacklist', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (Power::exist('App_Blacklist_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (Power::exist('App_Blacklist_Edit')) {
            $listButtonArr[] = array(
                'plain' => 'true', 'id' => 'bt_list_menu', 'text' => '操作', 'class' => 'bt_list_menu'
            );
        }
        if (Power::exist('App_Blacklist_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array(
            'type' => 'button',
            'id' => 'bt_list_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        );
        return $this->view->setVars([
            'List'       => Template::createList('list', 'App_Blacklist', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取黑名单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180614
     */
    public function getAppBlacklistAction()
    {
        if (!Power::exist('App_Blacklist')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        $page = $this->request->getPost('page', 'int');
        $rows = $this->request->getPost('rows', 'int');
        try {
            $data = App::getAppBlacklists($page, $rows);
            foreach ($data['rows'] as &$row) {
                $row['status'] = $this->appBackStatus[$row['status']] ;
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存黑名单
     *
     * create by xjq 20180614
     */
    public function addAppBlackAction()
    {
        if (!Power::exist('App_Blacklist_Add')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $postData = $this->request->getPost();
            if (!Tool::getValue($postData, 'packageName', null)) {
                return $this->sendErrorResponse(400, '包名必填');
            }
            App::addAppBlacklist($postData);
            return $this->sendSuccessResponse('添加成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 应用黑名单表单
     *
     * create by xjq 20180614
     */
    public function appBlackFormAction()
    {
        $this->view->pick('appserver/appBlackForm');
        Assets::importJs('js/appserver/appBlackForm.js');
    }

    /**
     * 删除黑名单
     *
     * create by xjq 20180614
     */
    public function delAppBlackAction()
    {
        if (!Power::exist('App_Blacklist_Del')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $id = $this->request->getPost('id', 'string');
            if (!$id) {
                return $this->sendErrorResponse('400', '缺少参数');
            }
            App::delAppBlacklist($id);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 启用配置
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180614
     */
    public function enableAppBlacklistAction()
    {
        try {
            $id = $this->request->getPost('id', 'string');
            if (!$id) {
                return $this->sendErrorResponse('400', '缺少参数');
            }
            App::changeAppBlacklistStatus($id, ['status' => 1]);
            return $this->sendSuccessResponse('配置已经成功启用');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 禁用配置
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180614
     */
    public function disableAppBlacklistAction()
    {
        try {
            $id = $this->request->getPost('id', 'string');
            if (!$id) {
                return $this->sendErrorResponse('400', '缺少参数');
            }
            App::changeAppBlacklistStatus($id, ['status' => 2]);
            return $this->sendSuccessResponse('配置已经成功禁用');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }


    /**
     * 学校防火墙
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180614
     */
    public function schoolFirewallAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI();
        Assets::importJs('js/appserver/schoolFirewall.js');
        $this->view->pick('appserver/schoolFirewall');
        Template::exists('App_SchoolFirewall', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (Power::exist('App_SchoolFirewall_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (Power::exist('App_SchoolFirewall_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $schools = XhschoolInfo::getSchoolArray();
        $schools['ALL'] = '公共';
        $schools['']    = '全部学校';

        $schools = array_reverse($schools, true);
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_school', 'data' => $schools, 'default' => '' ,
            'style' => 'width:180px;');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'App_SchoolFirewall', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'          => Template::createForm('App_SchoolFirewall'),
            'FormButton'    => Template::createButtonToolBar(Main::createFormButton('App_SchoolFirewall'))
        ]);
    }

    /**
     * 获取防火墙
     *
     * create by xjq 20180614
     */
    public function getSchoolFirewallAction()
    {
        if (!Power::exist('App_SchoolFirewall')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $schoolId = $this->request->getPost('schoolId', 'string');
            $page = $this->request->getPost('page', 'int');
            $rows = $this->request->getPost('rows', 'int');
            $key = $this->request->getPost('key', 'string');
            $conditionArr = [];
            if ($schoolId) {
                $conditionArr['schoolId'] = $schoolId;
            }
            if ($key) {
                $conditionArr['keyword'] = $key;
            }
            $data = App::getSchoolFirewall($page, $rows, $conditionArr);
            Tool::runTimestamp($data, ['updateAt' => 'updateAt']);
            $status = [0 => '删除' , 1 => '正常' ];
            $schools = School::getSchools(true);
            foreach ($data['rows'] as &$row) {
                $row['show'] = $row['show'] == false ? '否' : '是' ;
                $row['status'] = $status[$row['status']];
                $row['schoolName'] = $row['schoolId'] == 'ALL' ? '公共' : (isset($schools[$row['schoolId']]) ? $schools[$row['schoolId']] : '' );
            }
            unset($row);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 学校选择
     *
     * @param $packName
     *
     * create by xjq 20180622
     */
    public function schoolChooseAction($packName)
    {
        $this->view->pick('appserver/schoolChoose');
        Assets::easyUI('js/appserver/schoolChoose.js');
        Template::exists('School_Info', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars([
            'rightList' => Template::createList('rightList', 'School_Info', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
                'field' => ['iSchoolId', 'sSchoolName'],
                'tableAttr' => ['title' => '学校列表'],
            ]),
            'leftList' => Template::createList('leftList', 'School_Info', [
                'field' => ['iSchoolId', 'sSchoolName'],
                'tableArr' => ['title' => '已选择的学校'],
            ]),
        ]);
    }


    /**
     * 防火墙表单
     * create by xjq 20180614
     */
    public function schoolFirewallFormAction()
    {
        $this->view->pick('appserver/schoolFirewallForm');
        Assets::importJs('js/appserver/schoolFirewallForm.js');
    }

    /**
     * 新增学校防火墙
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180614
     */
    public function addSchoolFirewallAction()
    {
        if (!Power::exist('App_SchoolFirewall_Add')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $postData = $this->request->getPost();
            if (!$postData['schoolId'] || !$postData['packageName']) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            if ($postData['schoolId'] == 'ALL') {
                App::addAllSchoolFirewall([
                    'name'        => $postData['name'],
                    'packageName' => $postData['packageName'],
                    'show'        => Tool::getValue($postData, 'show', 0) == 1 ? true : false
                ]);
            } else {
                App::addSchoolFirewall([
                    'schoolIds'   => explode(',', $postData['schoolId']),
                    'name'        => $postData['name'],
                    'packageName' => $postData['packageName'],
                    'show'        => Tool::getValue($postData, 'show', 0) == 1 ? true : false
                ]);
            }

            return $this->sendSuccessResponse('新增成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 修改学校防火墙
     *
     * create by xjq 20180614
     */
    public function modifySchoolFireWallAction()
    {
        if (!Power::exist('App_SchoolFirewall_Edit')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $postData = $this->request->getPost();
            if (!$postData['schoolId'] || !$postData['packageName']) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            App::modifySchoolFirewall($postData['schoolId'], $postData['packageName'], [
                'name'        => $postData['name'],
                'show'        => Tool::getValue($postData, 'show', 0) == 1 ? true : false
            ]);
            return $this->sendSuccessResponse('修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }


    /**
     * 删除学校防火墙
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180614
     */
    public function delSchoolFirewallAction()
    {
        if (!Power::exist('App_SchoolFirewall_Del')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $ids = $this->request->getPost('ids');
            if (!$ids) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            App::delSchoolFirewall($ids);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }


    /**
     * 待上架的应用列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180619
     */
    public function stayShelfListAction()
    {
        if (!Power::exist('App_StayShelf')) {
            return $this->sendViewError('没有权限');
        }
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/appserver/stayShelfList.js');
        $this->view->pick('appserver/stayShelfList');
        Template::exists('App_StayShelf', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (Power::exist('App_StayShelf_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_menu', 'text' => '版本审核',
                'class' => 'bt_list_menu');
        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'App_StayShelf', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取待上架的应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180619
     */
    public function getStayShelfAction()
    {
        if (!Power::exist('App_StayShelf')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $page = $this->request->getPost('page', 'int');
            $rows = $this->request->getPost('rows', 'int');
            $key  = $this->request->getPost('key', 'string');
            $data = App::getAppStayShelfLists($page, $rows, [
                'keyword' =>  $key
            ]);
            foreach ($data['rows'] as $index => &$row) {
                $row = array_merge($row, $row['appVersion']);
                unset($row['appVersion']);
            }
            unset($row);
            $this->runApplicationEnum($data['rows']);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 同意应用上架
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180619
     */
    public function agreeStayShelfAction()
    {
        try {
            $appIdArr       = $this->request->getPost('appIdArr', 'string');
            $versionCodeArr = $this->request->getPost('versionCodeArr', 'string');
            if (!$appIdArr || !$versionCodeArr) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $dealNum = count($appIdArr);
            $successNum = 0;
            $errorNum = 0;
            foreach ($appIdArr as $index => $appId) {
                $versionCode = Tool::getValue($versionCodeArr, $index, '');
                if ($versionCode) {
                    $successNum++;
                    App::agreeAppStayShelf($appId, $versionCode);
                } else {
                    $errorNum++;
                }
            }
            return $this->sendSuccessResponse("应用上架成功，总共处理{$dealNum}个,成功{$successNum}个，失败{$errorNum}个");
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 拒绝应用上架
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180619
     */
    public function refuseStayShelfAction()
    {
        try {
            $appIdArr       = $this->request->getPost('appIdArr', 'string');
            $versionCodeArr = $this->request->getPost('versionCodeArr', 'string');
            if (!$appIdArr || !$versionCodeArr) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $dealNum = count($appIdArr);
            $successNum = 0;
            $errorNum = 0;
            foreach ($appIdArr as $index => $appId) {
                $versionCode = Tool::getValue($versionCodeArr, $index, '');
                if ($versionCode) {
                    $successNum++;
                    App::refuseAppStayShelf($appId, $versionCode);
                } else {
                    $errorNum++;
                }
            }
            return $this->sendSuccessResponse("拒绝应用上架成功，总共处理{$dealNum}个,成功{$successNum}个，失败{$errorNum}个");
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 下架应用列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by xjq 20180619
     */
    public function offShelfListAction()
    {
        if (!Power::exist('App_OffShelf')) {
            return $this->sendViewError('没有权限');
        }
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/appserver/offShelfList.js');
//        $this->view->pick('appserver/offShelfList');
        Template::exists('App_OffShelf', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();

//        if (Power::exist('App_OffShelf_Edit')) {
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_recover', 'text' => '恢复上架',
//'icon' => 'fa-refresh');
//        }
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_menu', 'text' => '版本审核',
//'class' => 'bt_list_menu');
//        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
//        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
//'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'App_OffShelf', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
//                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }


    /**
     * 获取下架应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180619
     */
    public function getOffShelfAction()
    {
        if (!Power::exist('App_OffShelf')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $page = $this->request->getPost('page', 'int');
            $rows = $this->request->getPost('rows', 'int');
            $data = App::getAppOffShelfLists($page - 1, $rows);
            $this->runApplicationEnum($data['rows']);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 回复上架
     *
     * create by xjq 20180619
     */
    public function recoverOffShelfAction()
    {
        if (!Power::exist('App_OffShelf_Edit')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        try {
            $packageName = $this->request->getPost('packageName', 'string');
            $version     = $this->request->getPost('version', 'string');
            if (!$packageName || !$version) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            App::recoverOffShelf($packageName, $version);
            return $this->sendSuccessResponse('恢复应用上架成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }
}